<template>
  <div v-if="knowledge" class="knowledge-detail">
    <div class="mb-6 flex justify-between items-center">
      <h2 class="text-2xl font-bold">{{ knowledge.title }}</h2>
      <el-button @click="goBack" type="primary" plain>返回</el-button>
    </div>
    
    <el-card shadow="hover" class="mb-6">
      <div class="content-section">
        <h3 class="text-lg font-bold mb-2">内容</h3>
        <p class="whitespace-pre-line">{{ knowledge.content }}</p>
      </div>
    </el-card>
    
    <el-card v-if="knowledge.imageUrl" shadow="hover" class="mb-6">
      <div class="image-section">
        <h3 class="text-lg font-bold mb-2">图片</h3>
        <el-image 
          :src="knowledge.imageUrl" 
          fit="contain"
          :preview-src-list="[knowledge.imageUrl]"
          class="detail-image"
        />
      </div>
    </el-card>
    
    <el-card shadow="hover">
      <div class="time-section">
        <h3 class="text-lg font-bold mb-2">时间信息</h3>
        <p><strong>创建时间:</strong> {{ formatDateTime(knowledge.createTime) }}</p>
        <p><strong>更新时间:</strong> {{ formatDateTime(knowledge.updateTime) }}</p>
      </div>
    </el-card>
  </div>
  <div v-else class="text-center py-10">
    <el-empty description="未找到知识项"></el-empty>
    <el-button class="mt-4" @click="goBack" type="primary">返回列表</el-button>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue';
import axios from 'axios';
import { ElMessage } from 'element-plus';

export default {
  name: 'KnowledgeDetail',
  props: {
    id: {
      type: [String, Number],
      required: true
    }
  },
  setup(props, { emit }) {
    const knowledge = ref(null);
    
    const fetchKnowledge = async () => {
      try {
        const response = await axios.get(`/api/knowledge/${props.id}`);
        knowledge.value = response.data;
      } catch (error) {
        console.error('获取知识详情失败:', error);
        ElMessage.error('获取知识详情失败');
      }
    };
    
    const goBack = () => {
      emit('back');
    };
    
    const formatDateTime = (dateTimeStr) => {
      if (!dateTimeStr) return '未知';
      const date = new Date(dateTimeStr);
      return new Intl.DateTimeFormat('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit',
        hour12: false
      }).format(date);
    };
    
    onMounted(() => {
      fetchKnowledge();
    });
    
    return {
      knowledge,
      goBack,
      formatDateTime
    };
  }
}
</script>

<style scoped>
.knowledge-detail {
  max-width: 800px;
  margin: 0 auto;
}

.detail-image {
  max-height: 400px;
  width: 100%;
  object-fit: contain;
}

.content-section, .image-section, .time-section {
  padding: 10px 0;
}
</style> 